#include "elementmap.h"
#include <QNetworkReply>

QString ElementMap::host;
QString ElementMap::port;
QString ElementMap::map_name;
QNetworkAccessManager ElementMap::manager;
ElementMap::ElementMap(int layer, int x, int y)
{
    this->layer = layer+1;
    this->x = x;
    this->y = y;
    if(this->layer==0) {
        this->map = QPixmap(256,256);
        this->map.fill(Qt::transparent);
        return;
    }
    this->map.load(":/res/loading.png");
    QString url = "http://" + host + ":"+port+"/v1/tilemap/tile/" + map_name +
            "/" + QString("%1/%2/%3.png").arg(this->layer).arg(y).arg(x);
    reply = manager.get(QNetworkRequest(QUrl(url)));
    connect(reply, &QNetworkReply::finished, this, [=](){
        QByteArray data = reply->readAll();
        reply->deleteLater();
        this->map.loadFromData(data);
        emit map_update();
    });
}

bool ElementMap::isEqual(int layer, int x, int y)
{
    return this->layer == layer+1 && this->x == x && this->y == y;
}

const QPixmap& ElementMap::getMap()
{
    return map;
}

void ElementMap::setHost(QString host)
{
    ElementMap::host = host;
}

void ElementMap::setPort(QString port)
{
    ElementMap::port = port;
}

void ElementMap::setMapName(QString map_name)
{
    ElementMap::map_name = map_name;
}
